/**
 * 
 */
package com.alianzamedica.controllers.prescription;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.objectsearch.sqlsearch.ObjectSearch;
import org.objectsearch.web.tools.FormatDateTool;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Doctor;
import com.alianzamedica.businessobject.Prescription;
import com.alianzamedica.controllers.constants.ActionConstants;
import com.alianzamedica.tools.Enviroment;

/**
 * @author RMarquez_Inf
 * 
 */
public class ListPrescriptionAction extends Action {
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.
	 * ActionMapping, org.apache.struts.action.ActionForm,
	 * javax.servlet.ServletRequest, javax.servlet.ServletResponse)
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		

		String sPageNum = request.getParameter("pageNum");
		Integer pageNum = 1;
		if (sPageNum != null && sPageNum.trim().length() > 0) {
			try {
				pageNum = Integer.valueOf(sPageNum);
			} catch (Exception e) {
			}
		}
		
		HttpSession session = request.getSession();
		Doctor doctor = (Doctor) session.getAttribute("doctor");
		Prescription prescription = new Prescription();
		prescription.setDoctorId(doctor.getId());
		
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		search.setDefaultDialect(ObjectSearch.MYSQL_DIALECT);

		Integer totalPages = search.getTotalPages(prescription);
		request.setAttribute("totalPages", totalPages);
		ArrayList pagedQuery = search.getPagedQuery(prescription, null,
				pageNum, ActionConstants.PAGE_SIZE);
		ArrayList<Prescription> prescriptions = pagedQuery;
		
		FormatDateTool formatDate = new FormatDateTool();
		request.setAttribute("formatDate", formatDate);
		
		request.setAttribute("prescriptions", prescriptions);

		return mapping.findForward("success");
	}
}
